<?php

declare(strict_types=1);

namespace app\xapply\controller;

use app\xapply\middleware\Auth;
use app\xapply\model\Login;
use app\xapply\Xapply;
use think\facade\Db;

class Profile extends Xapply
{

    protected $middleware = [Auth::class];

    /**
     * 元数据
     * url: http://域名/xapply/profile/mine
     * doc: http://lutui.net/doc/app/profile-meta.html
     */
    public function mine()
    {
        $user = $this->getUserinfo();
        $thumb = $user['thumb'];
        if (!strstr($thumb, 'http')){
            $thumb = request()->domain().$thumb;
        }
        return json([
            'info' => [
                'nickname' => $user['nickname'],
                'url' => $thumb,
            ],
            'meta' => [],
            'update' => false,
            'items' => [],
        ]);
    }

    /**
     * 退出登录
     * url: http://域名/xapply/profile/logout
     * doc: http://lutui.net/doc/app/profile-logout.html
     */
    public function logout()
    {
        Login::destroy(function($query){
            $query->where('user_id', XAPPLY_UID);
        });
        return json(['logout' => 'success']);
    }

    /**
     * 修改密码
     * url: http://域名/xapply/profile/password
     * doc: http://lutui.net/doc/app/profile-password.html
     */
    public function password()
    {
        $password = $this->data['password'];
        if (empty($password)) {
            return json(['error' => '请输入新密码']);
        }
        $salt = set_salt(20);
        $new_pwd = set_password($password, $salt);
        $data = [
            'reg_pwd' => '',
            'salt' => $salt,
            'pwd' => $new_pwd,
            'update_time' => time(),
        ];
        Db::name('Admin')->where(['id' => XAPPLY_UID])->strict(false)->field(true)->update($data);
        return json(['error' => '']);
    }
}
